package com.example.depcontrol.aop;

import com.alibaba.fastjson2.JSONObject;
import com.example.depcontrol.anno.Log;
import com.example.depcontrol.mapper.OperateLogMapper;
import com.example.depcontrol.pojo.OperateLog;
import com.example.depcontrol.utils.JwtUtils;
import com.google.gson.JsonObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;

import java.time.LocalDateTime;
import java.util.Arrays;


@Slf4j
@Component
@Aspect
public class LogAspect {
    @Resource
    private HttpServletRequest req;
    @Resource
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.example.depcontrol.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //操作人ID，获取请求头中的JWT令牌，然后解析
        String jwt = req.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");

        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = joinPoint.getSignature().getName();

        //操作方法参数
        String methodParams = Arrays.toString(joinPoint.getArgs());//数组强转字符串

        //开始时间
        Long begin = System.currentTimeMillis();

        //操作方法返回值
        Object res = joinPoint.proceed();
        String returnValue = JSONObject.toJSONString(res);

        //操作耗时
        Long end = System.currentTimeMillis();
        Long costTime = end - begin;

        //记录日志操作
        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams, returnValue, costTime);
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志：{}", operateLog);

        return res;
    }
}
